<?php

namespace App\Http\Controllers\Pc;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Jobs\SavePdfController;
use App\Jobs\UpdateOrderSku;
use App\Jobs\WalmartOrderJob;
use App\Jobs\WarehouseLocationStatJob;
use App\Jobs\WarehouseStatJob;
use App\Models\Amazon_skulist;
use App\Models\Amazon_traffic;
use App\Models\BaseModel;
use App\Models\CloudHouse;
use App\Models\Datawhole;
use App\Models\InventoryModel;
use App\Models\SelfSpuInfoModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\AmazonSkulist;
use App\Models\AmazonOrderItem;
use App\Models\AmazonTraffic;
use App\Models\AmazonReport;
use App\Models\Shop;
use App\Models\ProductDetail;
use App\Models\DigitalModel;
use Illuminate\Support\Facades\Redis;

class TimingController extends Controller
{

    public function __construct(Request $request)
    {
        $this->model = new DigitalModel();
        $this->request = $request;
    }
    /**
     * 定时任务
     * request 参数
     */

    //计算补货状态
    public function amazon_buhuo_flow()
    {

//        $shopData =shop::where('platform_id', 5)->get(['Id', 'store_user'])->toArray();
        //前两周的数据分析出需要补货的产品
        $year = date('Y');
        $month = date('m');
        $day = date('d', time());
        $last_month = date('m',strtotime("last month"));
        $lastDay = $this->get_lastday($year, $last_month);
        $thisDaySum = 7;
        $daySum = 14;
        $dataWhole_model = new Datawhole();
        //上周
        $startTime = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
        $endTime = date('Y-m-d 00:00:00', strtotime('-1 days',strtotime($year.'-'.$month.'-'.$day)));
        //上上周
        $startTimeTwo = date('Y-m-d 00:00:00', strtotime('-15 days',strtotime($year.'-'.$month.'-'.$day)));
        $endTimeTwo = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
        //月
        $startTimeMonth = date('Y-m-d 00:00:00', strtotime("-{$lastDay} days",strtotime($year.'-'.$month.'-'.$day)));
        $endTimeMonth = $endTime;
        $update_buhuo_status = '';
        $update_buhuo_status_two = '';
        $update_buhuo_status_three = '';
        $update_id = '';
        $update_id_two = '';
        $update_id_three = '';
        $echo = '';
        $echo_two = '';
        $echo_three = '';
                $sql = "SELECT
                    a.id,
                    a.plan_multiple,
                    a.sku,
                    a.sales_status,
                    a.buhuo_status,
                    s.fba_warehouse_id,
                    s.store_user 
                FROM
                    amazon_skulist a 
                LEFT JOIN shop s ON a.shop_id = s.Id
                ";
                $thisShop = json_decode(json_encode(Db::select($sql)),true);

                if (empty($thisShop)) {
                    echo 'none data', PHP_EOL;
                    return;
                }

                foreach ($thisShop as $value) {
                    $id = $value['id'];
                    $sku = $value['sku'];
                    //上周销量
                    $wholeParams['start_time'] = $startTime;
                    $wholeParams['end_time'] = $endTime;
                    $wholeParams['sku'] = $sku;
                    $dataWhole = $dataWhole_model->getDatawholeByOther($wholeParams);
                    $this_week_sale = $dataWhole['quantity_ordered'];
                    //上两周销量
                    $wholeParams['start_time'] = $startTimeTwo;
                    $wholeParams['end_time'] = $endTimeTwo;
                    $wholeParams['sku'] = $sku;
                    $dataWholeTwo = $dataWhole_model->getDatawholeByOther($wholeParams);
                    $before_week_sale =  $dataWholeTwo['quantity_ordered'];
                    //上个月销量
                    $wholeParams['start_time'] = $startTimeMonth;
                    $wholeParams['end_time'] = $endTimeMonth;
                    $wholeParams['sku'] = $sku;
                    $dataWholeMoth = $dataWhole_model->getDatawholeByOther($wholeParams);
                    $month_sale = $dataWholeMoth['quantity_ordered'];

                    $in_warehouse_inventory = null;//fba在仓库存
                    $reserved_inventory = null;//预留库存
                    $in_road_inventory = null;//在途库存

                    //根据sku找亚马逊库存
                    $AMZinventory = ProductDetail::where('sellersku',$sku)->get(['in_stock_num','in_bound_num','transfer_num','update_time'])->toArray();

                    if (!empty($AMZinventory)) {
                        $in_warehouse_inventory = $AMZinventory[0]['in_stock_num'];
                        $reserved_inventory = $AMZinventory[0]['transfer_num'];
                        $in_road_inventory = $AMZinventory[0]['in_bound_num'];
                    }
                    //合计库存
                    $total_inventory = $in_warehouse_inventory + $reserved_inventory + $in_road_inventory;
                    //近一周日均销售
                    if ($this_week_sale == 0) {
                        $this_week_daysales = 0;
                    } else {
                        $this_week_daysales = round($this_week_sale / $thisDaySum, 2);
                    }
                    //近两周日均销售
                    if ($before_week_sale == 0) {
                        $week_daysales = 0;
                    } else {
                        $week_daysales = round($before_week_sale / $daySum, 2);
                    }
                    //近一月日均销售
                    if ($month_sale == 0) {
                        $month_daysales = 0;
                    } else {
                        $month_daysales = round($month_sale / $lastDay, 2);
                    }
                    //库存可周转天数
                    if ($total_inventory != 0 && $week_daysales == 0) {
                        $inventory_turnover = 999;
                    } elseif ($total_inventory == 0 && $week_daysales == 0) {
                        $inventory_turnover = -1;
                    } elseif ($total_inventory == 0 && $week_daysales != 0) {
                        $inventory_turnover = 0;
                    } else {
                        $call_inventory = new \App\Models\DigitalModel();
                        if ($value['sales_status'] == 1) {  //爆款
                            $inventory_turnover = $call_inventory->inventoryTurnoverStatus($total_inventory, $this_week_daysales, $value['plan_multiple']);
                        } elseif ($value['sales_status'] == 2) {  //利润款
                            $inventory_turnover = $call_inventory->inventoryTurnoverStatus($total_inventory, $week_daysales, $value['plan_multiple']);
                        } elseif ($value['sales_status'] == 3) {   //清仓款
                            $inventory_turnover = $call_inventory->inventoryTurnoverStatus($total_inventory, $month_daysales, $value['plan_multiple']);
                        } else {
                            $inventory_turnover = $call_inventory->inventoryTurnoverStatus($total_inventory, $week_daysales, $value['plan_multiple']);
                        }
                    }
                    //补货提醒
                    if ($inventory_turnover >= 0 && $inventory_turnover < 60) {
                        if($value['buhuo_status']!=1){
                            $update_buhuo_status .= "WHEN '{$id}' THEN 1 ";
                            $update_id .= "'{$id}',";
                            $echo .= 'update:   ' . $sku . '______';
                            //$update = AmazonSkulist::where('id', $id)->update(['buhuo_status' => 1]);
                        }

                    }
                    if ($inventory_turnover >= 60 && $inventory_turnover < 90) {
                        if($value['buhuo_status']!=2) {
                            $update_buhuo_status_two .= "WHEN '{$id}' THEN 2 ";
                            $update_id_two .= "'{$id}',";
                            $echo_two .= 'update:   ' . $sku . '______';
                            //$update = AmazonSkulist::where('id', $id)->update(['buhuo_status' => 2]);
                        }
                    }
                    if ($inventory_turnover > 90) {
                        if($value['buhuo_status']!=3) {
                            $update_buhuo_status_three .= "WHEN '{$id}' THEN 3 ";
                            $update_id_three .= "'{$id}',";
                            $echo_three .= 'update:   ' . $sku . '______';
                            //$update = AmazonSkulist::where('id', $id)->update(['buhuo_status' => 3]);
                        }
                    }

                }
        if($update_buhuo_status==''&&$update_buhuo_status_two==''&&$update_buhuo_status_three==''){
            echo 'no_data_change!';
            die;
        }
//            }
//        }
        //去除多余的逗号
        $new_id = substr($update_id, 0, strlen($update_id) - 1);
        $new_id_two = substr($update_id_two, 0, strlen($update_id_two) - 1);
        $new_id_three = substr($update_id_three, 0, strlen($update_id_three) - 1);
        $update_sql = "update amazon_skulist
                                            set `buhuo_status` = Case id {$update_buhuo_status} END
                                            where `id` in ({$new_id})";
        $update = Db::update($update_sql);
        $update_sql_two = "update amazon_skulist
                                            set `buhuo_status` = Case id {$update_buhuo_status_two} END
                                            where `id` in ({$new_id_two})";
        $update_two = Db::update($update_sql_two);
        $update_sql_three = "update amazon_skulist
                                            set `buhuo_status` = Case id {$update_buhuo_status_three} END
                                            where `id` in ({$new_id_three})";
        $update_three = Db::update($update_sql_three);
        if ($update) {
            var_dump($echo);
        }
        if ($update_two) {
            var_dump($echo_two);
        }
        if ($update_three) {
            var_dump($echo_three);
        }

    }



    public function tongbu_data(){
        $skuData = AmazonSkulist::limit(500)->orderBy('tongbu_time','ASC')->get(['id', 'sku'])->toarray();
        foreach ($skuData as $val){
            $sku = $val['sku'];
            $id = $val['id'];
            //select('b.fnsku','b.parent_asin','b.asin','a.saihe_sku')
            $data = Db::table('saihe_product_detail as a')
                ->leftJoin('saihe_product as b','a.saihe_sku','=','b.sku')
                ->where('a.order_source_sku','=',$sku)
                ->select('b.client_sku','b.product_name_cn')
                ->first();
            if(!empty($data)){
                $amazon_data = Db::table('product_detail')
                    ->where('sellersku','=',$sku)
                    ->select('fnsku','parent_asin','asin')
                    ->first();
                if(!empty($amazon_data)){
                    $update['fnsku'] = $amazon_data->fnsku;
                    $update['father_asin'] = $amazon_data->parent_asin;
                    $update['asin'] = $amazon_data->asin;
                }
                $product_name = strstr($data->product_name_cn, $data->client_sku);
                if ($product_name === false) {
                    $product_name = $data->product_name_cn;
                }
                $update['tongbu_time'] = time();
                $update['product_name'] = $product_name;
                $update['custom_sku'] = $data->client_sku;
                $res = Db::table('amazon_skulist')
                    ->where('id',$id)
                    ->update($update);
                if(!$res){
                    echo '____'.$val['sku'].'fail____';
                }
            }else{
                $amazon_data = Db::table('product_detail')
                    ->where('sellersku','=',$sku)
                    ->select('fnsku','parent_asin','asin')
                    ->first();
                if(!empty($amazon_data)){
                    $update['fnsku'] = $amazon_data->fnsku;
                    $update['father_asin'] = $amazon_data->parent_asin;
                    $update['asin'] = $amazon_data->asin;
                }
                $update['product_name'] = '';
                $update['custom_sku'] = '';
                $update['tongbu_time'] = time();
                $res = Db::table('amazon_skulist')
                    ->where('id',$id)
                    ->update($update);
                if(!$res){
                    echo '____'.$val['sku'].'fail____';
                }else{
                    echo '____'.$val['sku'].'____';
                }
            }
        }
    }

    public function tongbu_saihe_data(){
        $skuSql = "SELECT
        id,
        sku
        FROM
        `amazon_buhuo_detail`
        WHERE
        `custom_sku` is null or`custom_sku`=''";
        $skuData = DB::select($skuSql);
        foreach ($skuData as $val){
            $sku = $val->sku;
            $id = $val->id;
            $data = Db::table('saihe_product_detail as a')
                ->leftJoin('saihe_product as b','a.saihe_sku','=','b.sku')
                ->where('a.order_source_sku','=',$sku)
                ->select('a.client_sku','b.product_name_cn')
                ->first();
            $product_name='';
            if(!empty($data)){
                if($data->client_sku!=''&&$data->client_sku!=null){
                    $product_name = strstr($data->product_name_cn, $data->client_sku);
                    if ($product_name === false) {
                        $product_name = $data->product_name_cn;
                    }
                    $update1 = Db::table('amazon_skulist')
                        ->where('sku',$sku)
                        ->update(['product_name'=>$product_name, 'custom_sku'=>$data->client_sku]);
                    if(!$update1){
                        echo $sku.'__fail_one__';
                    }
                    $update2 = Db::table('amazon_buhuo_detail')
                        ->where('id',$id)
                        ->update(['custom_sku'=>$data->client_sku
                        ]);
                    if(!$update2){
                        echo $sku.'__fail_two__';
                    }
                }

            }
        }
    }

    //获取上个月的最大日期
    public function get_lastday($year, $month)
    {
        if ($month == 2) {
            $lastday = $this->is_leapyear($year) ? 29 : 28;

        } elseif ($month == 4 || $month == 6 || $month == 9 || $month == 11) {
            $lastday = 30;

        } else {
            $lastday = 31;

        }
        return $lastday;
    }


    //同步没有获取到父asin的数据
    public function tongbu_fatherASin(){
        $product_detail = DB::table('product_detail')->where('parent_asin','!=','')->orderBy('tongbu_time','ASC')->select('id','shop_id','sellersku','fnsku','asin','parent_asin')->limit(500)->get();
        $product_data = json_decode(json_encode($product_detail), true);
        $a = 0;
        $b = 0;
        foreach ($product_data as $val){
            $time = time();
            $update = DB::table('product_detail')->where('id',$val['id'])->update(['tongbu_time'=>$time]);
            $skulist = DB::table('amazon_skulist')->where('sku',$val['sellersku'])->select('id')->first();
            $arr = [];
//            $product_name = '';
            if(empty($skulist)){
                $saihe = DB::table('saihe_product_detail as a')
                    ->leftjoin('saihe_product as b','a.saihe_sku','=','b.sku')
                    ->where('a.order_source_sku',$val['sellersku'])
                    ->select('b.client_sku','b.product_name_cn','b.small_image_url','b.product_group_sku')
                    ->first();
                if(!empty($saihe)){
                    if(isset($saihe->product_name_cn)){
                            $product_name = strstr($saihe->product_name_cn, $saihe->client_sku);
                        }
                    if ($product_name === false) {
                        $product_name = $saihe->product_name_cn;
                    }
                    $arr['custom_sku'] = $saihe->client_sku;
                    $arr['img'] = $saihe->small_image_url;
                    $arr['product_name'] = $product_name;
                    $arr['spu'] = $saihe->product_group_sku;
                }
                $arr['shop_id'] = $val['shop_id'];
                $arr['time'] = $time;
                $arr['sku'] = $val['sellersku'];
                $arr['fnsku'] = $val['fnsku'];
                $arr['asin'] = $val['asin'];
                $arr['father_asin'] = $val['parent_asin'];
                $insert = DB::table('amazon_skulist')->insert($arr);
                if($insert) echo 'success : '.$a++;
            }else{
                echo 'null : '.$b++;
            }
        }
    }

    //同步提交补货计划时没有获取到库存sku的数据
    public function tongbu_kucun(){
        $warehouse = DB::table('saihe_warehouse')->where('type','=',3)->select('id')->get();
        $warehouse = json_decode(json_encode($warehouse), true);
        $warehouse = array_column($warehouse,'id');
        $saihe_inventory = DB::table('saihe_inventory')->where('seller_sku','!=','')
            ->where('good_num','!=',0)
            ->whereIn('warehouse_id',$warehouse)
            ->orderBy('tongbu_time','ASC')
            ->select('id','client_sku','seller_sku')
            ->limit(500)->get();
        $saihe_inventory = json_decode(json_encode($saihe_inventory), true);
        $a = 0;
        $b = 0;
        foreach ($saihe_inventory as $val){
            $time = time();
            $update = DB::table('saihe_inventory')->where('id',$val['id'])->update(['tongbu_time'=>$time]);
            $skulist = DB::table('amazon_skulist')->where('sku',$val['seller_sku'])->select('id')->first();
            $arr = [];
            if(empty($skulist)){
                $saihe = DB::table('saihe_product_detail as a')
                    ->leftjoin('saihe_product as b','a.saihe_sku','=','b.sku')
                    ->where('a.order_source_sku',$val['seller_sku'])
                    ->select('b.client_sku','b.product_name_cn','b.small_image_url','b.product_group_sku')
                    ->first();
                if(!empty($saihe)){
                    if(isset($saihe->product_name_cn)){
                        $product_name = strstr($saihe->product_name_cn, $saihe->client_sku);
                    }
                    if ($product_name === false) {
                        $product_name = $saihe->product_name_cn;
                    }
                    $arr['custom_sku'] = $saihe->client_sku;
                    $arr['img'] = $saihe->small_image_url;
                    $arr['product_name'] = $product_name;
                    $arr['spu'] = $saihe->product_group_sku;
                }
                $arr['sku'] = $val['seller_sku'];
                $arr['time'] = $time;
                $amazon = DB::table('product_detail')->where('sellersku',$val['seller_sku'])->select('id','shop_id','fnsku','asin','parent_asin')->first();
                if(!empty($amazon)){
                    $arr['shop_id'] = $amazon->shop_id;
                    $arr['fnsku'] = $amazon->fnsku;
                    $arr['asin'] = $amazon->asin;
                    $arr['father_asin'] = $amazon->parent_asin;
                }
                $insert = DB::table('amazon_skulist')->insert($arr);
                if($insert) echo 'success : '.$a++;
            }else{
                echo 'null : '.$b++;
            }
        }
    }

    //重新生成补货计划的pdf
    // plan_id=计划id
    public function addtasks_son(){
        $param = $this->request->all();
        $plan_id = $param['plan_id'];

        $type = $param['type']??1;
            $pdf_data['plan_id'] = $plan_id;
            $pdf_data['type'] = $type;
            $user = DB::table('users')->where('Id',276)->select('token')->first();
            if(!empty($user)){
                $pdf_data['user_info']['user_id'] = 276;
                $pdf_data['token'] = $user->token;
            }

            $pdf_data['request_status'] = 4;
            $pdf = new SavePdfController();
            try {
                $pdf::runJob($pdf_data);
            } catch(\Exception $e){
                db::rollback();// 回调
                return 'pdf加入队列失败';
            }
    }

    //定时生成补货计划pdf
    public function create_pdf(){
        $request = DB::table('amazon_buhuo_request')->whereIn('request_status',[4,5])->where('is_pdf','=',0)->where('old_plan_id','=',0)->select('id','request_userid','request_status')->first();
        if(empty($request)){
            echo 'none';
            die;
        }
        $pdf = DB::table('save_pdf_log')->where('plan_id','=',$request->id)->select('id')->first();
        if(!empty($pdf)){
            $update = DB::table('amazon_buhuo_request')->where('id','=',$request->id)->update(['is_pdf'=>1]);
            if($update){
                echo 'update:success___';
                die;
            }else{
                echo 'update:fail___';
                die;
            }
        }else{
            $pdf_data['plan_id'] = $request->id;
            $pdf_data['user_info']['user_id'] = $request->request_userid;
            $user = DB::table('users')->where('Id',$request->request_userid)->select('token')->first();
            $pdf_data['request_status'] = $request->request_status;
            $pdf_data['token'] = $user->token;
            $pdf = new SavePdfController();
            try {
                $pdf::runJob($pdf_data);
            } catch(\Exception $e){
                echo 'pdf加入队列失败___';
            }
        }
    }

    //定时更新货件信息并重新采集没获取到地址的pdf
    public function shippment_status(){
        //找到需要更新状态的货件
        $request = DB::table('amazon_create_goods')->where('sprider_status',1)->where('type',1)->whereIn('ShipmentStatus',['WORKING','SHIPPED','IN_TRANSIT','IN_TRANSIT','DELIVERED','CHECKED_IN'])->select('shop_id','serial_no')->get();
        //找到没获取到pdf的货件
        $request2 = DB::table('amazon_create_goods')->where('sprider_pdf_status',0)->where('type',1)->select('shop_id','serial_no','box_ids')->get();
        if($request->isEmpty()&&$request2->isEmpty()) {
            echo 'none';
            die;
        }
        //加入队列更新状态
        foreach ($request as $val) {
            $redis_json = json_encode(['shop_id' => $val->shop_id, 'shippment_id' => $val->serial_no, 'status' => 1]);
            Redis::Lpush('creategoods_status', $redis_json);
        }
        //加入队列重新采集pdf
        var_dump($request2);
        foreach ($request2 as $val2) {
            $boxarray = explode(',', $val2->box_ids);
            $boxcount = count($boxarray);
            $redis_json2 = json_encode(['shop_id' => $val2->shop_id, 'shippment_id' => $val2->serial_no, 'page_size' => $boxcount]);
            var_dump($redis_json2);
            Redis::Lpush('creategoods_pdf', $redis_json2);
        }
    }

    //重新采集货件信息
    public function shippment_repeat(){
        $request = DB::table('amazon_create_goods')->where('file_name','')->where('type',1)->select('shop_id','serial_no')->get();
        if($request->isEmpty()){
            echo 'none';
            die;
        }
        foreach ($request as $val){
            $redis_json = json_encode(['shop_id' => $val->shop_id,'shippment_id' => $val->serial_no,'status' => 0]);
            Redis::Lpush('creategoods_status', $redis_json);
        }
    }

    //每日凌晨2点将需要采集的报告加入队列
    public function get_report(){
        $shop = DB::table('shop')->where('platform_id',5)->where('new_access_token','!=','')->whereIn('state',[1,3])->select('Id')->get();
        foreach ($shop as $val){
            $start_time1 = date('Y-m-d',strtotime("-180 day")).'T00:00:00';
            $end_time1 = date('Y-m-d',strtotime("-7 day")).'T00:00:00';
            $start_time2 = date('Y-m-d',strtotime("-26 day")).'T00:00:00';
            $end_time2 = date('Y-m-d').'T00:00:00';
//            $redis_json = json_encode(['shop_id' => $val->Id,'report_type' => 'GET_FBA_INVENTORY_AGED_DATA' , 'start_time'=>$start_time1,'end_time'=>$end_time1]);
//            Redis::Lpush('report_task_list', $redis_json);
            $redis_json = json_encode(['shop_id' => $val->Id,'report_type' => 'GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA' , 'start_time'=>$start_time2,'end_time'=>$end_time2]);
            Redis::Lpush('report_task_list', $redis_json);
        }
    }


    //每过3分钟把sku数据加入补货状态更新队列
    public function buhuo_status(){
        $sku = DB::table('self_sku')->where('status',1)->select('sku','old_sku','sale_status','plan_multiple')->get()->toArray();
        foreach ($sku as $val){
            if($val->old_sku!=null&&$val->old_sku!=''){
                $redis_json = ['sku'=>$val->old_sku,'sale_status'=>$val->sale_status,'plan_multiple'=>$val->plan_multiple];
                Redis::Lpush('update_buhuo_status', $redis_json);
            }else{
                $redis_json = ['sku'=>$val->sku,'sale_status'=>$val->sale_status,'plan_multiple'=>$val->plan_multiple];
                Redis::Lpush('update_buhuo_status', $redis_json);
            }
        }
    }

    public function task_news(){
        $day = date('d');
        if($day>14){
            $oneday = date('Y-m-28');
        }else{
            $oneday = date('Y-m-14');
        }
        $today = date('Y-m-d');
        $date = date("w",strtotime($oneday));
        if($date==6){
            $oneday = date('Y-m-d',strtotime('+2 days',strtotime($oneday)));
        }
        if($date==0){
            $oneday = date('Y-m-d',strtotime('+1 days',strtotime($oneday)));
        }
        $news_oneday = date('Y-m-d',strtotime('-5 days',strtotime($oneday)));
        if($today<$oneday&&$today>$news_oneday){
            $task = DB::table('tasks as a')
                ->leftJoin('tasks_son as b','a.Id','=','b.task_id')
                ->where('a.class_id',15)
                ->where('a.state',3)
                ->whereIn('b.state',[1,2])
                ->select('a.Id','a.user_fz','b.user_id','a.create_time','a.feedback_content2')
                ->get()
                ->toArray();
            if(!empty($task)){
                foreach ($task as $val){
                    if(empty($val->feedback_content2)){
                        $arr['task_id'] = $val->Id;
                        $arr['user_fs'] = $val->user_fz;
                        $arr['user_js'] = $val->user_id;
                        $arr['type'] = 1;
                        $arr['content'] = '已接近下次会议时间，请尽快完成任务并反馈任务进度！';
                        $insert = DB::table('tasks_news')->insert($arr);
                        if($insert){
                            // 如有接收人，给接收人发送站内消息
                            if (!empty($data['user_js'])) {
                                $content = "任务：{$data['task_name']}，有发送给您的消息！";
                                $tiding = DB::table('tidings')->insertGetId(
                                    ["user_fs" => $data['user_fs'], "user_js" => $data['user_js'], "title" => '任务内消息', "content" => $content, "object_id" => $data['task_id'], "object_type" => 1, "type" => 1, "create_time" => now()]
                                );
                                if ($tiding) {
                                    $this->redis_tiding($tiding, intVal($data['user_fs']), intVal($data['user_js']), '任务内消息', $content, $data['task_id'], 1, 1);
                                }
                            }
                        }
                    }else{
                        continue;
                    }
                }
            }else{
                die;
            }
        }else{
            die;
        }
    }

    public function checkOut(){
        $task = Redis::RPOP('cloud_outRequest');
        if(!empty($task)){
            $baseModel = new BaseModel();
            foreach ($task as $v){
                $createtime = date('Y-m-d H:i:s');
                $detail = DB::table('amazon_buhuo_detail')->where('request_id',$v->id)->where('custom_sku','like','%ZUHE%')->select('custom_sku','air_num','shipping_num','courier_num','custom_sku_id')->get();
                if(!empty($detail)){
                    foreach ($detail as $d){
                        //获取子成员sku
                        $custom_skuArr = $baseModel->GetGroupCustomSku($d->custom_sku);

                        $num = $d->air_num + $d->shipping_num + $d->courier_num;
                        //所有子成员的调拨数跟组合sku的发货计划数量一致
                        $zuheSku[$d->custom_sku] = $num;
                        foreach ($custom_skuArr as $c){
                            if(isset($customSku_list[$c])){
                                $customSku_list[$c] += $num;
                            }else{
                                $customSku_list[$c] = $num;
                            }
                        }
                    }
                    $params['order_no'] = rand(100,999).time();
                    $transfers['order_no'] = $params['order_no'];
                    $transfers['total_num'] = 0;
                    $transfers['sku_count'] = count($customSku_list);
                    $transfers['out_house'] = 3;
                    $transfers['in_house'] = 5;
                    $transfers['type'] = 2;
                    $transfers['yj_arrive_time'] = $params['yj_arrive_time'];
                    $transfers['user_id'] = $v->request_userid;
                    $transfers['text'] = '发货计划'.$v->id.'组合商品调拨出库';
                    $transfers['createtime'] = $createtime;
                    $total_num = 0;
                    //生成调拨数据
                    $transfers_id = DB::table('goods_transfers')->insertGetId($transfers);
                    //生成调拨明细数据
                    foreach ($customSku_list as $key=>$val){
                        $customskus[] = $val['custom_sku'];
                        $detail['order_no'] = $params['order_no'];
                        $detail['custom_sku'] = $key;
                        $spu = DB::table('self_custom_sku')->where('custom_sku',$key)->orWhere('old_custom_sku',$key)->select('spu','id','spu_id')->first();
                        if(!empty($spu)){
                            $detail['spu'] = $spu->spu;
                            $detail['spu_id'] = $spu->spu_id;
                            $detail['custom_sku_id'] = $spu->id;
                        }else{
                            $detail['spu'] = '';
                            $detail['spu_id'] = 0;
                            $detail['custom_sku_id'] = 0;
                        }
                        $detail['createtime'] = $createtime;
                        $detail['transfers_num'] = $val;
                        $total_num += $val;
                        $insert_detail = DB::table('goods_transfers_detail')->insert($detail);
                    }
                    //修改调拨总数
                    $update =  DB::table('goods_transfers')->where('id',$transfers_id)->update(['total_num'=>$total_num]);
                    $params['type'] = 'CGTH';
                    $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                    try {
                        $cloud::outhouseJob($params);
                    } catch(\Exception $e){
                        Redis::Lpush('out_house_fail',$params['order_no']);
                    }
                }
            }
        }
    }

    public function updateData(){
        $params = $this->request->all();
        $start = $params['start'];
        $end = $params['end'];
        $data = DB::table('cloudhouse_record as a')
            ->leftJoin('goods_transfers_detail as b', function($join)
            {
                $join->on('a.order_no','=','b.order_no')
                    ->on('a.custom_sku_id','=','b.custom_sku_id');
            })
            ->whereIn('a.type_detail',[2,9])
            ->where('a.createtime','>',$start)
            ->where('a.createtime','<',$end)
            ->select('a.custom_sku_id','b.contract_no','a.order_no','a.id')->get()->toArray();
        $cloudhouse_custom_sku = DB::table('cloudhouse_custom_sku')->select('contract_no','custom_sku_id','price')->get()->toArray();
        $arr = [];
        foreach ($cloudhouse_custom_sku as $c){
            $arr[$c->contract_no][$c->custom_sku_id] = $c->price;
        }
        foreach ($data as $b){
            if(isset($arr[$b->contract_no][$b->custom_sku_id])){
                $update = DB::table('cloudhouse_record')->where('id',$b->id)->update(['price'=>$arr[$b->contract_no][$b->custom_sku_id]]);
                if($update) {
                    echo $b->contract_no.'-'.$b->custom_sku_id.'</br>';
                }
            }
        }


    }

//    public function updateData(){
//        $params = $this->request->all();
////        $con = $params['contract_no'];
//        $con_data = DB::table('cloudhouse_contract')->whereIn('contract_no',['PO2211021','PO2211020','PO2211019','PO2211023','PO2301037'])->select('color_name','spu_id','id','color_identifying')->get();
//        foreach ($con_data as $v){
//            if($v->color_identifying){
//                $base = DB::table('self_spu')->where('id',$v->spu_id)->select('base_spu_id')->first();
//                if(!empty($base)){
//                    $base_spu_id = $base->base_spu_id;
//                    $colordata = DB::table('self_spu_color as a')->leftJoin('self_color_size as b','a.color_id','=','b.id')->where('a.base_spu_id',$base_spu_id)->select('b.name','b.identifying')->get();
//                    if(!empty($colordata)){
//                        foreach ($colordata as $c){
//                            if($v->color_name == $c->name){
//                                DB::table('cloudhouse_contract')->where('id',$v->id)->update(['color_identifying'=>$c->identifying]);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }

//    public function updateData(){
//
//       $contract = DB::table('cloudhouse_contract_total')->where('contract_type','成品采购')->select('contract_no')->get();
//
//       $contract = json_decode(json_encode($contract),true);
//       $contractlist = array_column($contract,'contract_no');
//       $cloudhouse_contract = DB::table('cloudhouse_contract')->whereIn('contract_no',$contractlist)->select('spu','color_identifying','one_price','spu_id')->get();
//       $baseModel = new BaseModel();
//       foreach ($cloudhouse_contract as $c){
//           $base_id = DB::table('self_spu')->where('id',$c->spu_id)->select('base_spu_id')->first();
//           if(!empty($base_id)){
//               $color_id = DB::table('self_color_size')->where('identifying',$c->color_identifying)->select('id')->first();
//               if(!empty($color_id)){
//                   $self_spu_color = DB::table('self_spu_color')->where('base_spu_id',$base_id->base_spu_id)->where('color_id',$color_id->id)->select('price')->first();
//                   if(!empty($self_spu_color)){
//                       if($self_spu_color->price==0){
//                           DB::table('self_spu_color')->where('base_spu_id',$base_id->base_spu_id)->where('color_id',$color_id->id)->update(['price'=>$c->one_price]);
//                       }
//                   }else{
//                       continue;
//                   }
//               }else{
//                   continue;
//               }
//           }
//       }
//
//
//        $params = $this->request->all();
//        $con_data = DB::table('cloudhouse_contract_total')
//            ->whereIn('contract_no',['PO2303196','PO2303195','PO2303197','PO2303350','PO2303348','PO2304045','PO2304046','PO2304055','PO2304070','PO2304097','PO2304098','PO2304095','PO2304099','PO2304106','PO2304124','PO2304125','PO2305002','PO2305003'])
//            ->select('contract_no')->get();
//        $con_data = json_decode(json_encode($con_data),true);
//        $data = DB::table('cloudhouse_custom_sku')
//            ->whereIn('contract_no',['PO2303196','PO2303195','PO2303197','PO2303350','PO2303348','PO2304045','PO2304046','PO2304055','PO2304070','PO2304097','PO2304098','PO2304095','PO2304099','PO2304106','PO2304124','PO2304125','PO2305002','PO2305003'])
//            ->get();
//        $data = json_decode(json_encode($data),true);
//        $customArr = array();
//        foreach ($data as $d){
//            if(isset($customArr[$d['contract_no']])){
//                array_push($customArr[$d['contract_no']],$d);
//            }else{
//                $customArr[$d['contract_no']][0] = $d;
//            }
//        }
//        $updateNum=0;
//        foreach ($con_data as $v){
//            $count = 0;
//            $price = 0;
//            if(isset($customArr[$v['contract_no']])){
//                foreach ($customArr[$v['contract_no']] as $val){
//                    print_r($val);
//                    $count+=$val['num'];
//                    $price+=$val['num']*$val['price'];
//                }
//            }
//            $update = DB::table('cloudhouse_contract_total')->where('contract_no',$v['contract_no'])->update(['total_count'=>$count,'total_price'=>$price]);
//            if($update){
//                $updateNum++;
//            }
//        }
//        echo $updateNum;
//    }

//    public function updateData(){
//
//        $params = $this->request->all();
//
//        $baseModel = new BaseModel();
//
//        $goods_transfers = DB::table('goods_transfers')->where('order_no',$params['order_no'])->first();
//
//        $goods_transfers_detail = DB::table('goods_transfers_detail')->where('order_no',$params['order_no'])->get()->toArray();
//        $detailArr = [];
//
//        foreach ($goods_transfers_detail as $g){
//            $detailArr[$g->custom_sku_id] = $g->contract_no;
//        }
//        $log = DB::table('cloudhouse_location_log')->where('order_no',$params['order_no'])->select('custom_sku_id','num')->get();
//        $skuArr = [];
//
//        foreach ($log as $v){
//            if(isset($skuArr[$v->custom_sku_id])){
//                $skuArr[$v->custom_sku_id] += $v->num;
//            }else{
//                $skuArr[$v->custom_sku_id] = $v->num;
//            }
//        }
//
//        $recordArr = [];
//        $record = DB::table('cloudhouse_record')->where('order_no',$params['order_no'])->select('custom_sku_id','num','warehouse_id')->get();
//        $warehouse_id = $goods_transfers->in_house;
//        foreach ($record as $r){
//            if(isset($recordArr[$r->custom_sku_id])){
//                $recordArr[$r->custom_sku_id] += $r->num;
//            }else{
//                $recordArr[$r->custom_sku_id] = $r->num;
//            }
//        }
//
//        db::beginTransaction();
//        foreach ($skuArr as $k=>$d){
//            if(isset($recordArr[$k])){
//                if($d!=$recordArr[$k]){
//                    $balance = $d-$recordArr[$k];
//                    $self_custom_sku = DB::table('self_custom_sku')->where('id',$k)->first();
//                    $custom_sku_pirce = DB::table('cloudhouse_custom_sku')->where('custom_sku_id',$k)
//                        ->where('contract_no',$detailArr[$k])->select('price')->first();
//                    if(empty($custom_sku_pirce)){
//                        db::rollback();// 回调
//                        return ['code' => 500, 'msg' => '未查询到合同单价--' . $v['custom_sku']];
//                    }
//                    $query['price'] = $custom_sku_pirce->price;
//                    $query['warehouse_id'] = $warehouse_id;
//                    $query['custom_sku_id'] = $k;
//
//                    $query['num'] = $balance;
//                    $query['user_id'] = 1;
//                    $query['type'] = 2; //1为出2为入
//                    $res = $baseModel->UpCloudHousePrice($query);
//                    if ($res['type'] != 'success') {
//                        db::rollback();// 回调
//                        return ['code' => 500, 'msg' => '新增资产记录失败--' . $self_custom_sku->custom_sku];
//                    }
//
//                    $insertRecord['order_no'] = $params['order_no'];
//                    $insertRecord['spu'] = $self_custom_sku->spu;
//                    $insertRecord['spu_id'] = $baseModel->GetSpuId($self_custom_sku->spu);
//                    $insertRecord['custom_sku_id'] = $self_custom_sku->id;
//                    $insertRecord['custom_sku'] = $self_custom_sku->custom_sku;
//                    $insertRecord['num'] = $balance;
//                    $insertRecord['createtime'] = date('Y-m-d H:i:s');
//                    $insertRecord['type'] = 2;
//                    $insertRecord['user_id'] = 1;
//                    $insertRecord['type_detail'] = $goods_transfers->type_detail;
//                    $insertRecord['warehouse_id'] = $warehouse_id;
//                    $insertRecord['shop_id'] = $goods_transfers->shop_id;
//                    if($warehouse_id==1){
//                        $increase_num = $self_custom_sku->tongan_inventory + $balance;
//                        $modify2Update['tongan_inventory'] = $increase_num;
//                    }
//                    if($warehouse_id==2){
//                        $increase_num = $self_custom_sku->quanzhou_inventory + $balance;
//                        $modify2Update['quanzhou_inventory'] = $increase_num;
//                    }
//
//                    $modify2 = DB::table('self_custom_sku')->where('id', $self_custom_sku->id)->update($modify2Update);
//                    if(!$modify2){
//                        db::rollback();// 回调
//                        return ['code' => 500, 'msg' => '入库失败--' . $self_custom_sku->custom_sku];
//                    }
//                    $insertRecord['price'] = $query['price'];
//                    $insertRecord['now_inventory'] = $increase_num;
//                    $insertRecord['now_total_price'] = $res['total_price'];
//                    $insertIn = DB::table('cloudhouse_record')->insert($insertRecord);
//                    if (!$insertIn) {
//                        db::rollback();// 回调
//                        return ['code' => 500, 'msg' => '新增入库记录失败--' . $self_custom_sku->custom_sku];
//                    }
//                }
//            }else{
//                $self_custom_sku = DB::table('self_custom_sku')->where('id',$k)->first();
//                if($goods_transfers->type_detail==2){
//                    $custom_sku_pirce = DB::table('cloudhouse_custom_sku')->where('custom_sku_id',$k)
//                        ->where('contract_no',$detailArr[$k])->select('price')->first();
//                    if(empty($custom_sku_pirce)){
//                        db::rollback();// 回调
//                        return ['code' => 500, 'msg' => '未查询到合同单价--' . $v['custom_sku']];
//                    }
//                    $query['price'] = $custom_sku_pirce->price;
//                }else{
//                    $query['price'] = $baseModel->GetCloudHousePrice($warehouse_id, $k);
//                }
//                $query['warehouse_id'] = $warehouse_id;
//                $query['custom_sku_id'] = $k;
//
//                $query['num'] = $d;
//                $query['user_id'] = 1;
//                $query['type'] = 2; //1为出2为入
//                $res = $baseModel->UpCloudHousePrice($query);
//                if ($res['type'] != 'success') {
//                    db::rollback();// 回调
//                    return ['code' => 500, 'msg' => '新增资产记录失败--' . $self_custom_sku->custom_sku];
//                }
//
//                $insertRecord['order_no'] = $params['order_no'];
//                $insertRecord['spu'] = $self_custom_sku->spu;
//                $insertRecord['spu_id'] = $baseModel->GetSpuId($self_custom_sku->spu);
//                $insertRecord['custom_sku_id'] = $self_custom_sku->id;
//                $insertRecord['custom_sku'] = $self_custom_sku->custom_sku;
//                $insertRecord['num'] = $d;
//                $insertRecord['createtime'] = date('Y-m-d H:i:s');
//                $insertRecord['type'] = 2;
//                $insertRecord['user_id'] = 1;
//                $insertRecord['type_detail'] = $goods_transfers->type_detail;
//                $insertRecord['warehouse_id'] = $warehouse_id;
//                $insertRecord['shop_id'] = $goods_transfers->shop_id;
//                if($warehouse_id==1){
//                    $increase_num = $self_custom_sku->tongan_inventory + $d;
//                    $modify2Update['tongan_inventory'] = $increase_num;
//                }
//                if($warehouse_id==2){
//                    $increase_num = $self_custom_sku->quanzhou_inventory + $d;
//                    $modify2Update['quanzhou_inventory'] = $increase_num;
//                }
//
//                $modify2 = DB::table('self_custom_sku')->where('id', $self_custom_sku->id)->update($modify2Update);
//                if(!$modify2){
//                    db::rollback();// 回调
//                    return ['code' => 500, 'msg' => '入库失败--' . $self_custom_sku->custom_sku];
//                }
//                $insertRecord['price'] = $query['price'];
//                $insertRecord['now_inventory'] = $increase_num;
//                $insertRecord['now_total_price'] = $res['total_price'];
//                $insertIn = DB::table('cloudhouse_record')->insert($insertRecord);
//                if (!$insertIn) {
//                    db::rollback();// 回调
//                    return ['code' => 500, 'msg' => '新增入库记录失败--' . $self_custom_sku->custom_sku];
//                }
//            }
//
//
//
//        }
//        db::commit();
////                   else{
////                       $update_transfers_detail = DB::table('goods_transfers_detail')->where('custom_sku_id',$v->custom_sku_id)->where('order_no',$v->out_no)
////                           ->update(['receive_num'=>$v->num]);
////                       if(!$update_transfers_detail){
////                           db::rollback();// 回调
////                           echo '修改transfers_detail失败--'.$v->out_no.'--'.$v->custom_sku_id.'</br>';
////                       }
////                       $update_transfers = DB::table('goods_transfers')->where('order_no',$v->out_no)
////                           ->update(['receive_total_num'=>$v->num,'is_push'=>3]);
////                      if(!$update_transfers){
////                           db::rollback();// 回调
////                           echo '修改goods_transfers失败--'.$v->out_no;
////                       }
////                       $update_box_detail = DB::table('goods_transfers_box_detail')->where('id',$goods_transfers_box_detail[0]->id)->update(['shelf_num'=>$v->num]);
////                       if(!$update_box_detail){
////                           db::rollback();// 回调
////                           echo '修改box_detail失败--'.$v->out_no.'--'.$v->custom_sku_id.'</br>';
////                       }
////                       $update_box = DB::table('goods_transfers_box')->where('id',$goods_transfers_box->id)->update(['onshelf_num'=>$v->num]);
////                       if(!$update_box){
////                           db::rollback();// 回调
////                           echo '修改box失败--'.$v->out_no.'</br>';
////                       }
////                       $update_location_num =DB::table('cloudhouse_location_num')->where('id',$location_num->id)->update(['num'=>$balance_num]);
////                       if(!$update_location_num){
////                           db::rollback();// 回调
////                           echo '修改location_num失败--'.$v->out_no.'--'.$v->custom_sku_id.'--'.$location_num->id.'</br>';
////                           die;
////                       }
////                       $update_custom_sku =DB::table('self_custom_sku')->where('id',$v->custom_sku_id)->update(['quanzhou_inventory'=>$balance_inventory]);
////                       if(!$update_custom_sku){
////                           db::rollback();// 回调
////                           echo '修改custom_sku失败--'.$v->out_no.'--'.$v->custom_sku_id.'</br>';
////                       }
////                       $insert['custom_sku_id'] = $v->custom_sku_id;
////                       $insert['custom_sku'] = $v->custom_sku;
////                       $insert['spu_id'] = $v->spu_id;
////                       $insert['spu'] = $v->spu;
////                       $insert['num'] = $v->num;
////                       $insert['now_num'] = $location_num_sum-$v->num;
////                       $insert['time'] = $date;
////                       $insert['remark'] = '泉州仓自发货漏下架补数据';
////                       $insert['type'] = 2;
////                       $insert['order_no'] = $v->out_no;
////                       $insert['location_id'] = $goods_transfers_box_detail[0]->location_ids;
////                       $insert['platform_id'] = $orderPlatform[$v->out_no];
////                       $insert['now_platform_num'] = $balance_num;
////                       $insertLog = DB::table('cloudhouse_location_log')->insert($insert);
////                       if(!$insertLog){
////                           db::rollback();// 回调
////                           echo '新增出入库记录失败--'.$v->out_no.'--'.$v->custom_sku_id;
////                       }
////
////                       $record['custom_sku_id'] = $v->custom_sku_id;
////                       $record['custom_sku'] = $v->custom_sku;
////                       $record['spu_id'] = $v->spu_id;
////                       $record['spu'] = $v->spu;
////                       $record['num'] = $v->num;
////                       $record['now_inventory'] = $v->quanzhou_inventory - $v->num;
////                       $record['remark'] = '泉州仓自发货漏出库补数据';
////                       $record['type'] = 1;
////                       $record['order_no'] = $v->out_no;
////                       $record['type_detail'] = 12;
////                       $record['warehouse_id'] = 2;
////                       $price = $baseModel->GetCloudHousePrice(2,$v->custom_sku_id);
////                       if($price==0){
////                           $priceData = DB::table('self_spu_info')->where('base_spu_id',$v->base_spu_id)->select('unit_price')->first();
////                           if(!empty($priceData)){
////                               $price = $priceData->unit_price;
////                           }
////                       }
////
////                       $query['warehouse_id'] = 2;
////                       $query['custom_sku_id'] = $v->custom_sku_id;
////                       $query['price'] = $price;
////                       $query['num'] = $v->num;
////                       $query['user_id'] = 1;
////                       $query['type'] = 1; //1为出2为入
////                       $res = $baseModel->UpCloudHousePrice($query);
////                       if($res['type']!='success'){
////                           db::rollback();// 回调
////                           echo '新增资产记录失败--'.$v->custom_sku_id;
////                       }
////
////                       $record['user_id'] = 1;
////                       $record['createtime'] = $date;
////                       $record['price'] = $price;
////                       $record['shop_id'] = $v->shop_id;
////                       $record['now_total_price'] = $res['total_price'];;
////                       $insertRecord = DB::table('cloudhouse_record')->insert($record);
////                       if(!$insertRecord){
////                           db::rollback();// 回调
////                           echo '新增出入库记录失败--'.$v->out_no.'--'.$v->custom_sku_id;
////                       }
////                   }
//
//
//
//
////        $params = $this->request->all();
////        $in_storage = DB::table('cloudhouse_custom_sku')->where('contract_no',$params['contract_no'])->get()->toArray();
////        $transfers['order_no'] = rand(100,999).time();
////        $transfers['total_num'] = 0;
////        $transfers['sku_count'] = 0;
////        $transfers['out_house'] = 4;
////        $transfers['in_house'] = 1;
////        $transfers['type'] = 1;
////        $transfers['yj_arrive_time'] = '2023-01-01 00:00:00';
////        $transfers['type_detail'] = 2;
////        $transfers['address'] = '';
////        $transfers['user_id'] = 1;
////        $transfers['confirm_id'] = 1;
////        $transfers['shop_id'] = 0;
////        $transfers['text'] = '艾诺科已入库数据导入';
////        $transfers['third_party_no'] = '';
////        $transfers['createtime'] = '2023-01-01 00:00:00';
////        $transfers['update_cause'] = 0;
////        $transfers['img_url'] = '';
////        $transfers['file_url'] = '';
////        $transfers['platform_id'] = 4;
////        $transfers['receive_platform_id'] = 0;
////        $contractArr = [];
////        db::beginTransaction();    //开启事务
////        foreach ($in_storage as $v){
////            $self_custom_sku = DB::table('self_custom_sku')->where('spu_id',$v->spu_id)->where('color',$v->color)->where('size',$v->size)->select('id','custom_sku')->first();
////            if(!empty($self_custom_sku)){
////                if(!in_array($v->contract_no,$contractArr)){
////                    $contractArr[] = $v->contract_no;
////                }
////
////                $transfers['sku_count']++;
////                $transfers['total_num'] += $v->num;
////
////                $detail['spu'] = $v->spu;
////                $detail['spu_id'] = $v->spu_id;
////                $detail['order_no'] = $transfers['order_no'];
////                $detail['custom_sku'] = $self_custom_sku->custom_sku;
////                $detail['custom_sku_id'] = $self_custom_sku->id;
////                $detail['transfers_num'] = $v->num;
////                $detail['receive_num'] = $v->num;
////                $detail['createtime'] = '2023-01-01 00:00:00';
////                $detail['receive_time'] = '2023-01-01 00:00:00';
////                $detail['contract_no'] = $v->contract_no;
////                $detail['is_settled'] = 1;
////                $insertDetail = DB::table('goods_transfers_detail')->insert($detail);
////                if(!$insertDetail){
////                    db::rollback();
////                    return '新增数据失败'.$v->id;
////                }
////            }
////        }
////        $transfers['contract_no'] = json_encode($contractArr);
////        $transfers['receive_total_num'] = $transfers['total_num'];
////        $insertTransfers = DB::table('goods_transfers')->insert($transfers);
////        if(!$insertTransfers){
////            db::rollback();
////            return '新增goods_transfers数据失败';
////        }
////        db::commit();
////        echo '数据生成成功';
//
//
//
////        $cloudhouse_record = DB::table('cloudhouse_record')->where('warehouse_id',3)->orderBy('createtime','asc')->get();
////        $self_custom_sku = DB::table('self_custom_sku')->where('is_cloud',1)->get();
////        $skuArr= [];
////        foreach ($self_custom_sku as $s){
////            $skuArr[$s->id] = $s->cloud_num;
////        }
////        $recordArr = [];
////        foreach ($cloudhouse_record as $v){
////            if($v->type==2){
////                if(isset($recordArr[$v->custom_sku_id])){
////                    $recordArr[$v->custom_sku_id] += $v->num;
////                }else{
////                    $recordArr[$v->custom_sku_id] = $v->num;
////                }
////            }else{
////                if(isset($recordArr[$v->custom_sku_id])){
////                    $recordArr[$v->custom_sku_id] -= $v->num;
////                }else{
////                    $recordArr[$v->custom_sku_id] = 0-$v->num;
////                }
////            }
////        }
////        foreach ($skuArr as $key=>$val){
////            if(isset($recordArr[$key])){
////                if($recordArr[$key]!=$val){
////                    echo $key.'库存 : '.$val.'---出入库差值 ：'.$recordArr[$key].'</br>';
//////                    DB::table('self_custom_sku')->where('id',$key)->update(['cloud_num'=>$recordArr[$key]]);
////                }
////            }
////        }
//
////       $cloudhouse_location_num = DB::table('cloudhouse_location_num as a')
////            ->leftJoin('cloudhouse_warehouse_location as b','a.location_id','=','b.id')
////            ->where('b.warehouse_id',$params['warehouse'])
//////            ->where('a.custom_sku_id','>',$params['start_id'])
//////            ->where('a.custom_sku_id','<',$params['end_id'])
////            ->select('a.*')->get();
////
////       $locationArr = [];
////       foreach ($cloudhouse_location_num as $v){
////           if(isset($locationArr[$v->custom_sku_id])){
////               $locationArr[$v->custom_sku_id] += $v->num;
////           }else{
////               $locationArr[$v->custom_sku_id] = $v->num;
////           }
////       }
////       $sku = DB::table('self_custom_sku')
//////           ->where('id','>',$params['start_id'])->where('id','<',$params['end_id'])
////           ->select('tongan_inventory','quanzhou_inventory','cloud_num','id')
////           ->get();
////       foreach ($sku as $ss){
////           if($params['warehouse']==1){
////               $inventory[$ss->id] = $ss->tongan_inventory;
////           }
////           if($params['warehouse']==2){
////               $inventory[$ss->id] = $ss->quanzhou_inventory;
////           }
////           if($params['warehouse']==3){
////               $inventory[$ss->id] = $ss->cloud_num;
////           }
////       }
////       $count = 0;
////       foreach ($locationArr as $k=>$d){
////               if(isset($inventory[$k])){
////                   if($inventory[$k]!=$d){
////                       echo $k.'--库存：'.$inventory[$k].'，库位库存：'.$d.'</br>';
////                       $count++;
////                   }
////               }
////       }
////       echo '总计：'.$count;
////        foreach ($arr as $v){
////            $goods_transfers_box = DB::table('goods_transfers_box')->where('order_no',$v)->select('box_num','onshelf_num','id')->first();
////            if($goods_transfers_box){
////                if($goods_transfers_box->onshelf_num<$goods_transfers_box->box_num){
////                    DB::table('goods_transfers_box')->where('id',$goods_transfers_box->id)->update(['onshelf_num'=>$goods_transfers_box->box_num,'status'=>2]);
////                    $goods_transfers_box_detail = DB::table('goods_transfers_box_detail')->where('box_id',$goods_transfers_box->id)->select('box_num', 'shelf_num','location_ids','custom_sku_id','id')->get();
////                    foreach ($goods_transfers_box_detail as $g){
////                        if($g->shelf_num<$g->box_num){
////                            DB::table('goods_transfers_box_detail')->where('id',$g->id)->update(['shelf_num'=>$g->box_num]);
////                            $data = DB::table('cloudhouse_location_num')->where('custom_sku_id',$g->custom_sku_id)->where('location_id',
////                                $g->location_ids)->select('id','num','platform_id')->get()->toArray();
////                            if(!empty($data)){
////                                $is_update = 0;
////                                foreach ($data as $d){
////                                    if($d->num>0&&$is_update==0){
////                                        $update = DB::table('cloudhouse_location_num')->where('id',$d->id)->update(['num'=>$d->num-$g->box_num]);
////                                        if($update){
////                                            $is_update = 1;
////                                            echo 'success :'.$v.'</br>';
////                                        }else{
////                                            echo 'fail :'.$v.'</br>';
////                                        }
////                                    }
////                                }
////
////                            }
////                        }
////                    }
////
////
////                }
////            }
////        }
//
////        $data = DB::table('amazon_place_order_detail')->where('order_id',10970)->where('custom_sku','like','AZUHE00035%')->where('color_name','=',null)
////            ->select('custom_sku','spu_id')->get();
////        $model = new BaseModel();
////        foreach ($data as $v){
////            $group = DB::table('self_group_custom_sku')->where('custom_sku',$v->custom_sku)->select('group_custom_sku_id')->get();
////            $arr = [];
////            foreach ($group as $g){
////                $color = DB::table('self_custom_sku')->where('id',$g->group_custom_sku_id)->select('color')->first();
////                $arr[] = $color->color;
////            }
////            $arr = array_unique($arr);
////            $res = $model->assemblyColor($arr,$v->spu_id);
////            if($res){
////                echo 'success</br>';
////            }
////
////        }
//
//    }

//    public function updateData(){
//        $sys_log = DB::table('sys_log')->where('user_id',465)->where('id','>',20712)->get()->toArray();
//        $spuModel = new SelfSpuInfoModel();
//        foreach ($sys_log as $v){
//            $output = json_decode($v->output,true);
//            if($output['type']=='success'){
//                $input = json_decode($v->input,true);
//                $self_spu_info = DB::table('self_spu_info')->where('base_spu_id',$input['base_spu_id'])->first();
//                if(empty($self_spu_info)){
//                    if(!isset($input['fabric_one'])){
//                        $input['fabric_one'] = 111;
//                    }
//                    if(!isset($input['washing_label_id'])){
//                        $input['washing_label_id'] = 111;
//                    }
//                    if(!isset($input['seller_point_desc'])){
//                        $input['seller_point_desc'] = 111;
//                    }
//                    if(!isset($input['unit_price'])){
//                        $input['unit_price'] = 111;
//                    }
//
//                    if(!isset($input['order_num_desc'])){
//                        $input['order_num_desc'] = 111;
//                    }
//                    if(isset($input['attr'])){
//                        unset($input['attr']);
//                    }
//                    $res = $spuModel->SaveSpuInfoM($input);
//
//                    echo $res['msg'].'--'.$v->id.'</br>';
//
//                }
//            }
//        }
//    }
    public function addData(){
        $params = $this->request->all();
//        $contractlist = DB::table('cloudhouse_contract_shoudongxiugai')->select('contract_no')->distinct()->get()->toArray();
//        $contractArr = array_column($contractlist,'contract_no');
        $con_data = DB::table('cloudhouse_contract')
            ->where('contract_no',$params['contract_no'])
            ->where('spu_id','!=',0)->where('color_identifying','!=','')->get();
        $con_data = json_decode(json_encode($con_data),true);
        foreach ($con_data as $v){
            $jsonData = json_decode($v['num_info']);
            $total = 0;
            foreach ($jsonData as $k=>$j){
                $total += $j;
                $setdata = DB::table('cloudhouse_custom_sku')
                    ->where('contract_no',$v['contract_no'])
                    ->where('spu_id',$v['spu_id'])
                    ->where('color',$v['color_identifying'])
                    ->where('size',$k)
                    ->select('id','num')->first();
                if(empty($setdata)){
                    $custom_sku = DB::table('self_custom_sku')->where('spu_id',$v['spu_id'])->where('color',$v['color_identifying'])->where('size',$k)->first();
                    if(!empty($custom_sku)){
                        $insert['spu'] = $v['spu'];
                        $insert['spu_id'] = $v['spu_id'];
                        $insert['color'] = $v['color_identifying'];
                        $insert['size'] = $k;
                        if($custom_sku->old_custom_sku){
                            $insert['custom_sku'] = $custom_sku->old_custom_sku;
                        }else{
                            $insert['custom_sku'] = $custom_sku->custom_sku;
                        }
                        $insert['custom_sku_id'] = $custom_sku->id;
                        $insert['color_name'] = $v['color_name'];
                        $insert['contract_no'] = $v['contract_no'];
                        $insert['num'] = $j;
                        $insert['is_push'] = 0;
                        $insert['price'] = $v['one_price'];
                        DB::table('cloudhouse_custom_sku')->insert($insert);
                    }else{
                        print_r($v['contract_no'].'-'.$v['spu_id'].'-'.$v['color_identifying'].'-'.$k."未生成sku\n");
                    }
                }else{
                    if($setdata->num!=$j){
                        $update = DB::table('cloudhouse_custom_sku')->where('id',$setdata->id)->update(['num'=>$j]);
                        if($update){
                            echo $setdata->id.'修改成功'.$setdata->num.'=>'.$j.'</br>';
                        }
                    }
                }
            }
        }
    }

    /**
     * @Desc: 保存上月库存sku库存变动
     * @return null
     * @throws \Exception
     * @author: Liu Sinian
     * @Time: 2023/3/3 16:09
     */
    public function saveCustomSkuMonthStockCount()
    {
        $params = $this->request->all();
        $model = new \App\Models\CustomSkuMonthStockCount();
        $result = $model->saveCustomSkuMonthStockCount($params);

        if (empty($result)){
            return $this->back('获取失败！');
        }

        return $this->back('获取成功', 200, $result);
    }

    public function check_data(){
        $params = $this->request->all();
//        $cloudhouse_contract_total = DB::table('cloudhouse_contract_total')->get();
//        foreach ($cloudhouse_contract_total as $v){
//           $cloudhouse_contract = DB::table('cloudhouse_contract')->where('contract_no',$v->contract_no)->get()->toArray();
//           if(empty($cloudhouse_contract)){
//               echo '明细为空：'.$v->contract_no.'</br>';
//           }else{
//               $count = 0;
//               foreach ($cloudhouse_contract as $d){
//                   $count += $d->count;
//               }
//               if($count!=$v->total_count){
//                   echo '数量不匹配：明细总数量为'.$count.',合同数量为'.$v->total_count.'合同号：'.$v->contract_no.'</br>';
//               }
//           }
//
//        }

//        $cloudhouse_contract = DB::table('cloudhouse_contract')->get();
//        $cloudhouse_contract = json_decode(json_encode($cloudhouse_contract),true);
//        foreach ($cloudhouse_contract as $v){
//            $count = $v['XXS']+$v['XS']+$v['S']+$v['M']+$v['L']+$v['XL']+$v['2XL']+$v['3XL']+$v['4XL']+$v['5XL']+$v['6XL']+$v['7XL']+$v['8XL'];
//            if($count!=$v['count']){
//                echo $v['contract_no'].':'.$v['spu'].':'.$v['color_identifying'].'</br>';
//            }
//        }
        $data = DB::table('fpx_order')
            ->where('status','>',1)
            ->where('warehouse_id',$params['warehouse_id'])
            ->select('out_no')
            ->get()->toArray();
        foreach ($data as $v){
            $record = DB::table('cloudhouse_record')->where('order_no',$v->out_no)->select('order_no')->first();
            if(empty($record)){
                echo $v->out_no.'</br>';
            }
        }

    }

    //抓取沃尔玛订单
    public function walmartOrder(Request $request)
    {
        $data = $request->all();

        if (!isset($data['type']) || !in_array($data['type'], [1,2])) {
            $this->back('type类型必传');
        }

        $job = new WalmartOrderJob($data);
        $job ->dispatch($data)->onQueue('walmart_order');
        return $this->back('获取成功', 200);
    }

    //更新定单渠道sku
    public function updateOrderSku(Request $request)
    {
        $data = $request->all();
        $job = new UpdateOrderSku($data);
        $job ->dispatch($data)->onQueue('update_order_sku');
        return $this->back('获取成功', 200);
    }

    //库位每日统计
    public function warehouseLocationStat(Request $request)
    {
        $data = $request->all();
        $job = new WarehouseLocationStatJob($data);
        $job ->dispatch($data)->onQueue('warehouse_location_stat');
        return $this->back('获取成功', 200);
    }

    //仓库每日/每日统计
    public function warehouseStat(Request $request)
    {
        $data = $request->all();

        if (!isset($data['type']) || !in_array($data['type'], ['day', 'month'])) {
            $this->back('type类型必传');
        }

        $job = new WarehouseStatJob($data);
        $job ->dispatch($data)->onQueue('warehouse_stat');
        return $this->back('获取成功', 200);
    }


    public function AlibabaTask(Request $request){
     

        $task_key = rand(100,999).time();
        $job = new \App\Http\Controllers\Jobs\AlibabaJobController;
        try {
            //code...
            $job::runJob($task_key);
            redis::set('queue_task:alibaba',$task_key);
        } catch (\Throwable $th) {
            //throw $th;
            var_dump($th->getMessage());
        }

    }

    public function InventoryDayTask(Request $request){
     

        $task_key = rand(100,999).time();
        $job = new \App\Http\Controllers\Jobs\InventoryDayJobController;
        try {
            //code...
            $job::runJob($task_key);
            redis::set('queue_task:inventory_day',$task_key);
        } catch (\Throwable $th) {
            //throw $th;
            var_dump($th->getMessage());
        }

   
        

        // $type = 1;
        // if($type==1){
        //     $start_time = date('Y-m-d 00:00:00',time()-86400*7);
        //     $end_time = date('Y-m-d 23:59:59',time()-86400);
        //     $i['find_day'] = 7;
        // }
        // if($type==2){
        //     $start_time = date('Y-m-d 00:00:00',time()-86400*30);

        //     $end_time = date('Y-m-d 23:59:59',time()-86400);
        //     $i['find_day'] = 30;
        // }
        // if($type==3){
        //     $start_time = date('Y-m-d 00:00:00',time()-86400*90);
        //     $end_time = date('Y-m-d 23:59:59',time()-86400);
        //     $i['find_day'] = 90;
        // }
        // $i['start_time'] = $start_time;
        // $i['end_time'] = $end_time;
        // echo '周转天数fasin缓存考试--天数-'.$i['find_day'].'--开始时间'. $i['start_time'].'--结束时间'. $i['end_time'] ."开始--\n";
        // $i['update_time'] = date('Y-m-d h:i:s',time());
        // $today = date('Y-m-d',time());

        // //查询fasin对应的sku  库存sku
        // $fasin_sku = db::table('self_sku')->where('fasin','!=','')->select(db::raw('group_concat(custom_sku_id) as custom_sku_ids'),'fasin')->groupby('fasin')->get();
        // $fasin_skus = [];
        // foreach ($fasin_sku as $fasv) {
        //     # code...
        //     if($cus_ids = explode(',',$fasv->custom_sku_ids)){
        //         $fasin_skus[$fasv->fasin] = $cus_ids;
        //     }
        // }


        // //获取库存sku库存
        // $cus_inventorys = db::table('self_custom_sku')->get();

        // $cus_inventory = [];
        // foreach ($cus_inventorys as $cv) {
        //     # code...
        //     $cus_inventory[$cv->id] = $cv->quanzhou_inventory+$cv->tongan_inventory+$cv->cloud_num;
        // }

        // //查询库存sku fba库存
        // $fba = [];
        // $cus_cache = db::table('cache_cus_today')->where('ds','like', "{$today}%")->get();
        // foreach ($cus_cache as $csv) {
        //     # code...
        //     $fba[$csv->custom_sku_id] = $csv->in_stock_num+$csv->transfer_num+$csv->in_bound_num;
        // }


        // //查询日报销量

        // $day_report_order = [];
        // $reports = Db::table('amazon_day_report')->whereBetween('ds', [$start_time, $end_time])->get()->toarray();
        // $report_ids = array_column($reports,'id');
        
        // $day_report =  Db::table('amazon_day_report_detail')->whereIn('report_id', $report_ids)->select('fasin',DB::raw('sum(sales_num) as orders'))->groupby('fasin')->get();


        // $fasin_order = [];
        // foreach ($day_report as $dv) {
        //     # code...
        //     $fasin_order[$dv->fasin] = $dv->orders;
        // }


        // $fasin_list = db::table('amazon_fasin')->where('is_self',1)->get();
        // foreach ($fasin_list as $key => $fv) {
        //     # code...
        //     //查询fasin 订单
        //     $fv->order = 0;
        //     if(isset($fasin_order[$fv->fasin])){
        //         $fv->order =$fasin_order[$fv->fasin];
        //     }
        //     $s_start_time = strtotime($start_time);
        //     $s_end_time = strtotime($end_time);
        //     $day = ceil(($s_end_time - $s_start_time) / 86400);
        //     $day_quantity_ordered = 0;
        //     if ($fv->order > 0) {
        //         $day_quantity_ordered = round($fv->order / $day, 2);
        //     }


        //     //查询fasin的库存sku
        //     $f_cus_ids = [];
        //     if(isset($fasin_skus[$fv->fasin])){
        //         $f_cus_ids = $fasin_skus[$fv->fasin];
        //     }


        //     //获取库存
        //     $here_inventory = 0;
        //     $fba_inventory = 0;
        //     foreach ($f_cus_ids as $f_cus_v) {
        //         # code...
        //         if(isset($cus_inventory[$f_cus_v])){
        //             $here_inventory +=$cus_inventory[$f_cus_v];
        //         }
        //         if(isset($fba[$f_cus_v])){
        //             $fba_inventory +=$fba[$f_cus_v];
        //         }
        //     }

        //           // //本地仓库存
        //     $fv->here_inventory_day = 999;
        //     //本地仓库存周转天数
        //     $fv->fba_inventory_day = 999;
        //     //fba仓库存周转天数
        //     if ($day_quantity_ordered == 0) {
        //         $fv->here_inventory_day = 999;
        //         $fv->fba_inventory_day = 999;
        //     }
    
        //     if ($fv->here_inventory == 0) {
        //         $fv->here_inventory_day = 0;
        //     }
        //     if ($fv->fba_inventory == 0) {
        //         $fv->fba_inventory_day = 0;
        //     }
    
        //     if ($day_quantity_ordered > 0 && $fv->here_inventory > 0) {
        //         //本地仓库存周转天数=同安库存/日销
        //         $fv->here_inventory_day = round($fv->here_inventory / $day_quantity_ordered, 2);
        //     }
        //     if ($day_quantity_ordered > 0 && $fv->fba_inventory > 0) {
        //         //fba库存周转天数=在仓+预留+在途/日销
        //         $fv->fba_inventory_day = round($fv->fba_inventory / $day_quantity_ordered, 2);
        //     }
        //     $i['here_days'] = $fv->here_inventory_day;
        //     $i['fba_days'] = $fv->fba_inventory_day;
        //     $i['fasin'] = $fv->fasin;
        //     $i['order'] = $fv->order;
        //     $i['fba_inventory'] =$fv->fba_inventory;
        //     $i['here_inventory'] =$fv->here_inventory;

        //     $re = db::table('inventory_day_fasin')->where('fasin',$i['fasin'])->where('find_day',$i['find_day'])->first();
        //     if($re){
        //         db::table('inventory_day_fasin')->where('id',$re->id)->update($i);
        //     }else{
        //         db::table('inventory_day_fasin')->insert($i);
        //     }
            
        // }


        //spu

        // $data = $request->all();

        // $type = $data['type']??1;
        // if($type==1){
        //     $start_time = date('Y-m-d 00:00:00',time()-86400*7);
        //     $end_time = date('Y-m-d 23:59:59',time()-86400);
        //     $i['find_day'] = 7;
        // }
        // if($type==2){
        //     $start_time = date('Y-m-d 00:00:00',time()-86400*30);
        //     $end_time = date('Y-m-d 23:59:59',time()-86400);
        //     $i['find_day'] = 30;
        // }
        // if($type==3){
        //     $start_time = date('Y-m-d 00:00:00',time()-86400*90);
        //     $end_time = date('Y-m-d 23:59:59',time()-86400);
        //     $i['find_day'] = 90;
        // }
        // $i['start_time'] = $start_time;
        // $i['end_time'] = $end_time;
        // $i['update_time'] = date('Y-m-d h:i:s',time());
        // // $res = db::table('local_sql')->get();
        // // var_dump($res);
        // // return $this->back('运行成功',200);


        // $today = date('Y-m-d',time());
        // //获取实时数据
        // $cachetodays = Db::table('cache_spu')->where('ds','like', "{$today}%")->get();
        // $fba = [];
        // if($cachetodays){
        //     foreach ($cachetodays as $cv) {
        //         # code...
        //         $fba[$cv->spu_id] = $cv->in_stock_num+$cv->transfer_num+$cv->in_bound_num;
        //     }

        // }

        // //获取最近库存数据
        // $cusdata =  Db::table('self_custom_sku')->select(db::raw('sum(quanzhou_inventory) as quanzhou_inventory'),db::raw('sum(tongan_inventory) as tongan_inventory'),db::raw('sum(cloud_num) as cloud_num'),'spu_id')->groupby('spu_id')->get();
        // $here = [];
        // if($cusdata){
        //     foreach ($cusdata as $cdv) {
        //         # code...
        //         $here[$cdv->spu_id] = $cdv->quanzhou_inventory+$cdv->tongan_inventory+$cdv->cloud_num;
        //     }
      
        // }


        // $list =  Db::table('cache_spu')->whereBetween('ds', [$start_time, $end_time])->select(db::raw('sum(order_num) as order_num'),'spu_id')->groupby('spu_id')->get();


        // foreach ($list as $v) {
        //     # code...
        //     $s_start_time = strtotime($start_time);
        //     $s_end_time = strtotime($end_time);
        //     $day = ceil(($s_end_time - $s_start_time) / 86400);
        //     $day_quantity_ordered = 0;
        //     if ($v->order_num > 0) {
        //         $day_quantity_ordered = round($v->order_num / $day, 2);
        //     }
            
        //     $v->fba_inventory = 0;
        //     if(isset($fba[$v->spu_id])){
        //         $v->fba_inventory  = $fba[$v->spu_id];
        //     }

        //     $v->here_inventory  = 0;
        //     if(isset($here[$v->spu_id])){
        //         $v->here_inventory  = $here[$v->spu_id];
        //     }

        //     // //本地仓库存
        //     $v->here_inventory_day = 999;
        //     //本地仓库存周转天数
        //     $v->fba_inventory_day = 999;
        //     //fba仓库存周转天数
        //     if ($day_quantity_ordered == 0) {
        //         $v->here_inventory_day = 999;
        //         $v->fba_inventory_day = 999;
        //     }
    
        //     if ($v->here_inventory == 0) {
        //         $v->here_inventory_day = 0;
        //     }
        //     if ($v->fba_inventory == 0) {
        //         $v->fba_inventory_day = 0;
        //     }
    
        //     if ($day_quantity_ordered > 0 && $v->here_inventory > 0) {
        //         //本地仓库存周转天数=同安库存/日销
        //         $v->here_inventory_day = round($v->here_inventory / $day_quantity_ordered, 2);
        //     }
        //     if ($day_quantity_ordered > 0 && $v->fba_inventory > 0) {
        //         //fba库存周转天数=在仓+预留+在途/日销
        //         $v->fba_inventory_day = round($v->fba_inventory / $day_quantity_ordered, 2);
        //     }
        //     $i['here_days'] = $v->here_inventory_day;
        //     $i['fba_days'] = $v->fba_inventory_day;
        //     $i['spu_id'] = $v->spu_id;

        //     $re = db::table('inventory_day_spu')->where('spu_id',$i['spu_id'])->where('find_day',$i['find_day'])->first();
        //     if($re){
        //         db::table('inventory_day_spu')->where('id',$re->id)->update($i);
        //     }else{
        //         db::table('inventory_day_spu')->insert($i);
        //     }
        // }
        //日销
        // var_dump($list);
      
    }


    // 开发中（默认）
    // 询价中-报价中（报价需求） self_spu_quotation_demand   status 1  0待报价  1报价中  2报价完成
    // 打样中1 
    // 打样完成 self_spu_proofing_demand  2
    // 已下单  amzon_place_order 1
    // 未发布  开合同 cloudhouse_contract
    // 已发布 手动点
    // Constant::SPU_STATUS
    //产品状态 self_spu  spu_status  //产品状态0 开发中  1待报价、2.报价中3报价完成，4待打样,5打样中、6打样完成、7已下单、8未发布、9已发布 、10缺货、11促销**% 、12清仓 、13下架（跟供应链）
    public function UpdateSpuStatus(){

        $time = date('Y-m-d',time()-86400);
        //询价
        $list_a = db::table('self_spu_quotation_demand')->get();
        //打样
        $list_b = db::table('self_spu_proofing_demand')->get();
        //下单
        $list_c = db::table('amazon_place_order_detail as a')->leftjoin('amazon_place_order_task as b','a.order_id','=','b.id')->where('creattime','>',$time)->get();

        //合同
        $list_d = db::table('cloudhouse_contract')->where('create_time','>',$time)->get();

        $data = [];

        foreach ($list_a as $av) {
            # code...
            if($av->status==0){$status = 1;}//待报价
            if($av->status==1){$status = 2;}//报价中
            if($av->status==2){$status = 3;}//报价完成
            $data[$av->spu_id] = $status;
        }
        foreach ($list_b as $bv) {
            # code...
            if($bv->status==0){$status = 4;}//待打样
            if($bv->status==1){$status = 5;}//打样中
            if($bv->status==2){$status = 6;}//打样完成
            $data[$bv->spu_id] = $status;
        }
        foreach ($list_c as $cv) {
            # code...
            $data[$cv->spu_id] = 7;//已下单
        }
        foreach ($list_d as $dv) {
            # code...
            $data[$dv->spu_id] = 8;//未完成
        }
        

        foreach ($data as $sid => $sts) {
            # code...
            db::table('self_spu')->where('id',$sid)->update(['spu_status'=>$sts,'spu_status_time'=>date('Y-m-d H:i:s',time())]);
        }

        // var_dump($data);


    }

    public function SyncLingxinToAmazonStatus(){
        $time = date('Y-m-d',time()-(14*86400));
        // $amazon = db::table('amazon_order_item')->where('amazon_time','>',$time)->get();
        $linxin = db::table('lingxing_amazon_order')->where('create_time','>',$time)->get();
        foreach ($linxin as $v) {
            # code...
            echo $v->amazon_order_id."\n";
            db::table('amazon_order_item')->where('amazon_order_id',$v->amazon_order_id)->update(['order_status'=>$v->order_status,'update_time'=>time()]);
        }
        echo '完成';
    }

    public function SyncLingxinToAmazon(){
        $time = date('Y-m-d',time()-86400);
        $amazon = db::table('amazon_order_item')->where('amazon_time','>',$time)->get();
        $linxin = db::table('lingxing_amazon_order_item')->where('create_time','>',$time)->get();

        $a_o = [];
        foreach ($amazon as $av) {
            # code...
            $key = $av->order_item_id.$av->seller_sku.$av->shop_id;
            $a_o[$key] = 1;
        }

        $new = [];
        foreach ($linxin as $lv) {
            # code...
            $keys = $lv->order_item_no.$lv->msku.$lv->shop_id;
            if(!isset($a_o[$keys])){
                echo $lv->id;
                $item['amazon_order_id'] = $lv->amazon_order_id;
                $item['shop_id'] = $lv->shop_id;
                $item['asin'] = $lv->product_no;
                $item['seller_sku'] = $lv->msku;
                $item['order_item_id'] = $lv->order_item_no;
                $item['quantity_ordered'] = $lv->quantity;
                $item['amount'] = $lv->item_price_amount;
                $item['item_tax'] = $lv->tax_amount;
                $item['order_status'] = $lv->order_status;
                $item['spu'] = $lv->spu;
                $item['spu_id'] = $lv->spu_id;
                $item['custom_sku_id'] = $lv->custom_sku_id;
                $item['sku_id'] = $lv->sku_id;
                $item['user_id'] = $lv->user_id;
                $item['fulfillment_channel'] = 'MFN';
                $item['title'] = 'lingxin';
                try {
                    //code...
                   $aos = db::table('amazon_order_item')->where('order_item_id',$lv->order_item_no)->where('seller_sku',$lv->msku)->where('shop_id',$lv->shop_id)->first();
                   if(!$aos){
                    db::table('amazon_order_item')->insert($item);
                   } 
                } catch (\Throwable $th) {
                    //throw $th;
                    echo $th->getMessage();
                }

            }
        }

        echo '完成';
    }

    public function addRole(){
        $params = $this->request->all();
        $power_id = $params['power_id'];
        $role = isset($params['role'])?$params['role']:'';
        if(empty($role)){
            $xt_role = DB::table('xt_role')->where('pid','!=',0)->get();
            foreach ($xt_role as $v){
                $role_join = DB::table('xt_powers_role_join')->where('role_id',$v->Id)->where('power_id',$power_id)->first();
                if(empty($role_join)){
                    DB::table('xt_powers_role_join')->insert(['role_id'=>$v->Id,'power_id'=>$power_id]);
                }
            }
        }else{
            foreach ($role as $v){
                DB::table('xt_powers_role_join')->insert(['role_id'=>$v,'power_id'=>$power_id]);
            }
        }
    }
}

